<?php

namespace App\Http\Logics;

use Curl;

class DingDing
{

    private $url;
    private $phones;
    private $secret;

    public function __construct($url, $secret, array $phones = [])
    {
        $this->url = $url;
        $this->secret = $secret;
        $this->phones = $phones;
        $this->sign();
        // https://oapi.dingtalk.com/robot/send?access_token=42ff724a860c0a51ad9680f51f9d16d49bca8d8c0332b678fedc953fc6ac5a38
        // SEC1f14cddd673bdb67b162f21e41d016027a6eb37e99ddf03e43320d2dd7addc01
    }

    protected function sign()
    {
        $time = millisecond();
        $sign = "{$time}\n{$this->secret}";
        $sign = hash_hmac('sha256', $sign, $this->secret, true);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        $this->url .= "&timestamp={$time}&sign={$sign}";
    }

    protected function sendMessage($data)
    {
        return Curl::to($this->url)
            ->withData($data)
            ->asJson()
            ->post();
    }

    public function text($text, $isAtAll = false)
    {
        $data = [
            'msgtype' => "text",
            'text' => [
                'content' => $text,
            ],
            'at' => [
                'atMobiles' => $this->phones,
                'isAtAll' => $isAtAll,
            ],
        ];
        return $this->sendMessage($data);
    }

    public function link($title, $text, $messageUrl, $picUrl = '')
    {
        $data = [
            'msgtype' => "link",
            'link' => [
                'text' => $text, // 消息内容。如果太长只会部分展示
                'title' => $title, // 消息标题
                'picUrl' => $picUrl, // 图片URL
                'messageUrl' => $messageUrl, // 点击消息跳转的URL
            ],
        ];
        return $this->sendMessage($data);
    }

    public function markdown($title, $text, $isAtAll = false)
    {
        $data = [
            'msgtype' => "markdown",
            'markdown' => [
                'title' => $title, // 首屏会话透出的展示内容
                'text' => $text, // markdown格式的消息, #### 杭州天气 @150XXXXXXXX \n> 9度，西北风1级，空气良89，相对温度73%\n> ![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)\n> ###### 10点20分发布 [天气](https://www.dingtalk.com) \n
            ],
            'at' => [
                'atMobiles' => $this->phones,
                'isAtAll' => $isAtAll,
            ],
        ];
        return $this->sendMessage($data);
    }
}
